<template>
  <div class="article-container">
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="分类列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @emptyQuery="emptyQuery" @receiveKeyword="receiveKeyword" class="toolbar">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('category:insert')">
                <el-button class="toolbar-button" @click="openSaveCategoryModal">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增分类
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('category:delete')">
                <el-button class="toolbar-button" @click="deleteMultiCategories">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>

          </tool-bar>

          <!--卡片里的内容-->
          <el-table
            slot="content"
            ref="categoryTable"
            :data="categoryData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectCategory"
            @select-all="selectCategory"
            :key="tableKey">
            <el-table-column
              align="center"
              type="selection"
              min-width="55">
            </el-table-column>
            <el-table-column
              prop="categoryName"
              label="分类名称"
              min-width="100">
            </el-table-column>
            <el-table-column
              prop="description"
              label="描述"
              min-width="500">
            </el-table-column>
            <el-table-column
              align="center"
              prop="sort"
              label="排序"
              min-width="60">
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="80">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.usable"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('category:update')"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="120">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="180">
              <template slot-scope="scope">
                <span v-if="!hasPermission('category:update') && !hasPermission('category:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('category:update')"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('category:delete')"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>
    <save-category-template
      :categoryFromParent="categoryForUpdate"
      @reloadTable="loadTableForCategory"
      ref="saveCategoryTemplate"></save-category-template>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar'
  import SaveCategoryTemplate from './subView/SaveCategoryTemplate'

  import {getCategoryByPage, deleteByIds, changeUsable, getCategoryById} from "../../network/viewsRequest/category";
  import {getTagByCid} from "../../network/viewsRequest/tag";
  import {hasPermission} from "../../common/permission";

  export default {
    name: 'CategoryView',
    data() {
      return {
        categoryData: [],
        multiSelections: [],
        query: {
          currentPage: 1,
          pageSize: 10,
          keyword: '', // toolbar中传递过来的搜索关键字
        },
        total: 0,
        categoryForUpdate: {}, // 回显时传递给模态框的分类信息
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 清空查询条件
       */
      emptyQuery() {
        let currentPage = this.query.currentPage;
        let pageSize = this.query.pageSize;
        this.query = {
          keyword: '',
          currentPage: currentPage,
          pageSize: pageSize,
        }
        this.loadTableForCategory();
      },
      /**
       * 点击多选框时触发的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectCategory(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 用户在点击分页插件时，获取用户点击到的是第几页
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        this.loadTableForCategory();
      },
      /**
       * 编辑分类
       * @param index 当前编辑分类的索引
       * @param row 当前编辑分类的那行内容
       */
      handleEdit(index, row) {
        // 1.根据id查询分类
        getCategoryById(row.id).then(res => {
          if (res.code == 1) {
            // 给categoryForUpdate赋值
            this.categoryForUpdate = res.data;
            // 打开模态框
            this.$refs.saveCategoryTemplate.show();
          } else {
            this.message({
              type: 'error',
              message: res.message
            });
            this.categoryForUpdate = {};
          }
        })
      },
      /**
       * 删除分类
       * @param index 需要删除分类的索引
       * @param row 需要删除分类的那行内容
       */
      handleDelete(index, row) {
        let delIds = [];
        delIds.push(row.id);
        this.deleteCategories(delIds);
      },
      /**
       * 用于删除分类的方法的具体逻辑
       * @param ids 需要删除分类的id的集合
       */
      deleteCategories(ids) {
        this.$confirm('是否要删除？注意：一旦删除无法恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteByIds(ids.join(",")).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              });
              // 刷新父组件中表格的数据
              this.loadTableForCategory();
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除操作已经被取消'
          })
        })
      },
      /**
       * 切换指定分类是否启用
       * @param row 该分类所对应的信息
       */
      changeUsable(row) {
        // TODO 用promise改写
        // 在停用的情况下，要先检查其下有没有可用的标签，有的话不可以停用
        if (row.usable == 0) {
          // 经过判断再进行操作
          // 1.查询该分类下有无标签，有的话不给停用
          getTagByCid(row.id).then(res => {
            if (res.code == 1) {
              if (res.data.length != 0) {
                this.$message({
                  type: 'error',
                  message: '该分类下仍然存在可用的标签，不能停用'
                });
                this.loadTableForCategory();
                return;
              }
            }
            // 2.进行操作
            this.changeUsableLogic(row.id, row.usable);
          });
        } else {
          // 直接进行操作
          this.changeUsableLogic(row.id, row.usable);
        }


      },
      /**
       * 切换是否启用具体操作的逻辑
       */
      changeUsableLogic(id, usable) {
        changeUsable(id, usable).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '操作成功'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
            this.loadTableForCategory();
          }
        });
      },
      /**
       * 接收子组件toolbar传递过来的搜索关键字keyword
       * @param keyword 搜索关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadTableForCategory();
      },
      /**
       * 获取分类数据，需要分页及条件搜索
       */
      loadTableForCategory() {
        getCategoryByPage(this.query).then(res => {
          if (res.code == 1) {
            this.categoryData = res.data.items;
            this.total = res.data.total;
          } else {
            this.categoryData = [];
            this.total = 0;
          }

        })
      },
      /**
       * 当用户点击`新增分类`时调用的方法
       */
      openSaveCategoryModal() {
        // 打开新增分类的模态框
        this.$refs.saveCategoryTemplate.show();
      },
      /**
       * 检查用户有没有进行了选择
       */
      checkSelected() {
        if (this.multiSelections.length == 0) {
          this.$message({
            type: 'error',
            message: '请先选择需要操作的记录！'
          });
          return false;
        }
        return true;
      },
      /**
       * 批量删除所选的分类
       */
      deleteMultiCategories() {
        if (this.multiSelections.length == 0) {
          this.$message({
            type: 'error',
            message: '请选择需要进行删除的分类信息'
          });
          return;
        }
        let delIds = this.multiSelections.map(item => {
          return item.id;
        });
        this.deleteCategories(delIds);
      }
    },
    created() {
      this.loadTableForCategory();
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.categoryData.length; i++) {
          key += this.categoryData[i].updateTime;
        }
        return key;
      }
    },
    components: {
      Card,
      Pagination,
      ToolBar,
      SaveCategoryTemplate
    }
  }
</script>

<style scoped>
  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .el-card {
    margin-top: 30px;
  }
  .editBtn {
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff
  }
  .button-all-container {
    vertical-align: bottom;
  }
  .btn-container {
    margin-right: 5px;
  }
</style>

<style>

  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 14px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }
  .button-all-container {
    display: inline-block;
  }
  .el-popup-parent--hidden {
    padding-right: 0px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
